import searchbar from './searchbar.js';
import autocomplete from '../../util/autocomplete.js';
import urlParser from '../../util/urlParser.js';
import places from '../../places/places.js';
import searchEngine from '../../util/searchEngine.js';
import funcs from '../../util/funcs.js';
var currentResponseSent = 0;

function showSearchbarPlaceResults(text, input, event, pluginName = 'places') {
  var responseSent = Date.now();

  if (pluginName === 'fullTextPlaces') {
    var searchFn = places.searchPlacesFullText;
    var resultCount = 4 - searchbar.getResultCount('places');
  } else {
    var searchFn = places.searchPlaces;
    var resultCount = 4;
  }

  // only autocomplete an item if the delete key wasn't pressed
  var canAutocomplete = event && event.keyCode !== 8;

  searchFn(text, (results) => {
    // prevent responses from returning out of order
    if (responseSent < currentResponseSent) {
      return;
    }

    currentResponseSent = responseSent;

    searchbar.reset(pluginName);

    results = results.slice(0, resultCount);

    results.forEach((result, index) => {
      var didAutocompleteResult = false;

      var searchQuery = searchEngine.getSearch(result.url);

      if (canAutocomplete) {
        // if the query is autocompleted, pressing enter will search for the result using the current search engine, so only pages from the current engine should be autocompleted
        if (
          searchQuery &&
          searchQuery.engine === searchEngine.getCurrent().name &&
          index === 0
        ) {
          var acResult = autocomplete.autocomplete(input, [searchQuery.search]);
          if (acResult.valid) {
            canAutocomplete = false;
            didAutocompleteResult = true;
          }
        } else {
          var autocompletionType = autocomplete.autocompleteURL(
            input,
            result.url
          );

          if (autocompletionType !== -1) {
            canAutocomplete = false;
          }

          if (autocompletionType === 0) {
            // the domain was autocompleted, show a domain result item
            var domain = new URL(result.url).hostname;

            searchbar.setTopAnswer(pluginName, {
              title: domain,
              url: domain,
              fakeFocus: true,
            });
          }
          if (autocompletionType === 1) {
            didAutocompleteResult = true;
          }
        }
      }

      var data = {
        url: result.url,
        metadata: result.tags,
        delete: function () {
          places.deleteHistory(result.url);
        },
      };

      if (searchQuery) {
        data.title = searchQuery.search;
        data.secondaryText = searchQuery.engine;
        data.icon = 'carbon:search';
      } else {
        data.title = urlParser.prettyURL(urlParser.getSourceURL(result.url));
        data.secondaryText = funcs.getRealTitle(result.title);
      }

      // show a star for bookmarked items
      if (result.isBookmarked) {
        data.icon = 'carbon:star-filled';
      }

      // create the item

      if (didAutocompleteResult) {
        // if this exact URL was autocompleted, show the item as the top answer
        data.fakeFocus = true;
        searchbar.setTopAnswer(pluginName, data);
      } else {
        searchbar.addResult(pluginName, data);
      }
    });
  });
}

function initialize() {
  searchbar.register('places', {
    index: 1,
    trigger: function (text) {
      r=!!text && text.indexOf('!') !== 0;
      console.log(text);
      console.log("places trigger "+r)
      return r;
    },
    showResults: showSearchbarPlaceResults,
  });

  searchbar.register('fullTextPlaces', {
    index: 2,
    trigger: function (text) {
      return !!text && text.indexOf('!') !== 0;
    },
    showResults: funcs.debounce(function () {
      console.log('@@@@@@@@@@@@places plugin showResults@@@@@@@@@@@@@@@@@@@@');
      if (searchbar.getResultCount('places') < 4 && searchbar.associatedInput) {
        showSearchbarPlaceResults.apply(
          this,
          Array.from(arguments).concat('fullTextPlaces')
        );
      } else {
        // can't show results, clear any previous ones
        searchbar.reset('fullTextPlaces');
      }
    }, 200),
  });
}

export default { initialize };
